<?php
	/*
	*	file: loginMod.php
	*
	*	contents: 	provides functions to check login username and password, user permissions, manage login errors.
	*				Login data and user permissions are stored in superglobal $_SESSION.
	*
	*	author: Federico Zanco
	*/



	/*
	* function checkLogin($unset)
	*
	* Input required: 	$unset: if true unset session data
	*					$_POST data: username and password strings posted by login page
	*
	* Output: 	if login data are posted from login page, check values, while if not posted
	*			it tris to check session data. If none of this are valid shows login page and
	*			notifies errors
	*
	* Author: Federico Zanco
	*/

	function checkLogin($unset) {
		//start a PHP session
		session_start();

		//if $unset is true unset session values
		if ($unset)
			session_unset();
		
		//if 'Accedi' button has been pressed then start a new login session
		if (isset($_POST['Accedi'])) {

			//unset old values
			session_unset();

			//get username and password posted
			$_SESSION['username'] = $_POST['username'];
			$_SESSION['password'] = $_POST['password'];
		}

		//if no username was posted show login page and notify error
		if ($_SESSION['username'] == "")
			showLogin("<div align=\"center\"><h2>Benvenuto</h2></div> <br /> Inserisci Nome e Password e premi Accedi per iniziare.
			");

		//if no password was posted show login page and notify error
		if ($_SESSION['password'] == "") 
			showLogin("Attenzione! Il campo Password &egrave; obbligatorio.
			");
	}



	/*
	* function checkPermissions()
	*
	* Input required:	none
	*
	* Output:	checks if user exists and retrieves user permissions from table users 
	*			if user doesn't exist shows login page and notify the error
	*
	* Author: Federico Zanco
	*/
		
	function checkPermissions() {
		//global mysql db connection
		global $con;
		
		//try to retrieve from users table user permissions
		$query = "SELECT * FROM users WHERE username=\"" . $_SESSION['username'] . "\"";
		$res = query($query, $con);
	
		//if any rows in result get permissions
		if (mysql_affected_rows($con) != 0)  {
			$row = mysql_fetch_assoc($res);
			$_SESSION['insert_auth'] = $row['insert_auth'];
			$_SESSION['edit_auth'] = $row['edit_auth'];
			$_SESSION['search_auth'] = $row['search_auth'];
			$_SESSION['department'] = $row['department'];
		} else {

			//else disconnect from db and show login with the error
			disconnect($con);
			session_unset();
			showLogin("Attenzione! Questo utente non ha i permessi impostati.
			");
		}
	}

?>